package com.anrongtec.zcpt.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.callback.StringDialogCallback;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.constant.JsonDataRestult;
import com.anrongtec.zcpt.constant.PreferenceKey;
import com.anrongtec.zcpt.constant.URLConstants;
import com.anrongtec.zcpt.model.AppModel;
import com.anrongtec.zcpt.model.Comment;
import com.anrongtec.zcpt.utils.GsonUtil;
import com.anrongtec.zcpt.utils.HttpUtil;
import com.anrongtec.zcpt.utils.PreferenceUtils;
import com.anrongtec.zcpt.utils.ToastShow;
import com.anrongtec.zcpt.utils.Util;
import com.google.gson.reflect.TypeToken;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class AppCommentPublishActivity extends BaseActivity implements View.OnClickListener, RatingBar.OnRatingBarChangeListener, TextWatcher {
    private AppCompatButton acb_comment_publish_cancle, acb_comment_publish_publish;
    private RatingBar rating_comment_publish_score;
    private EditText et_comment_publish_content;
    private Toolbar toolBar;
    private AppCompatButton btn_toolbar;

    private TextView tv_length;//显示字数

    private AppModel appModel;
    private static final float DEFAULT_STAR = 3.5f;
    private static final int DEFAULT_COMMENT_LENGTH = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleShow(false);
        setContentView(R.layout.activity_app_comment_publish);
        initData();
        initToolBar();
        initViews();
        initEvents();
    }

    @Override
    protected void initData() {

        appModel = (AppModel) getIntent().getSerializableExtra(Constant.DATA);

    }


    /**
     * 设置toolbar
     */
    private void initToolBar() {
        // toolbar
        toolBar = (Toolbar) findViewById(R.id.toolbar);
        toolBar.setTitle("发布评论");
        setSupportActionBar(toolBar);
        toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getSupportActionBar().setHomeButtonEnabled(true); // 这个小于4.0版本的默认值为true的。但是在4.0及其以上是false，该方法的作用：决定左上角的图标是否可以点击。没有向左的小图标。
        // true 图标可以点击 false
        // 不可以点击。
        getSupportActionBar().setDisplayHomeAsUpEnabled(true); // 给左上角图标的左边加上一个返回的图标
        // 。对应ActionBar.DISPLAY_HOME_AS_UP
        // getSupportActionBar().setDisplayShowHomeEnabled(true);
        // //使左上角图标是否显示，如果设成false，则没有程序图标，仅仅就个标题，否则，显示应用程序图标，对应id为android.R.id.home，对应ActionBar.DISPLAY_SHOW_HOME
        // getSupportActionBar().setDisplayShowCustomEnabled(true); //
        // 使自定义的普通View能在title栏显示，即actionBar.setCustomView能起作用，对应ActionBar.DISPLAY_SHOW_CUSTOM
        btn_toolbar = (AppCompatButton) findViewById(R.id.btn_toolbar_button);
    }

    @Override
    protected void initViews() {
        acb_comment_publish_cancle = (AppCompatButton) findViewById(R.id.acb_comment_publish_cancle);
        acb_comment_publish_publish = (AppCompatButton) findViewById(R.id.acb_comment_publish_publish);
        rating_comment_publish_score = (RatingBar) findViewById(R.id.rating_comment_publish_score);
        rating_comment_publish_score.setRating(DEFAULT_STAR);
        et_comment_publish_content = (EditText) findViewById(R.id.et_comment_publish_content);

        tv_length = (TextView) findViewById(R.id.tv_comment_length);
        tv_length.setText("0/"+DEFAULT_COMMENT_LENGTH);
    }

    @Override
    protected void initEvents() {
        acb_comment_publish_cancle.setOnClickListener(this);
        acb_comment_publish_publish.setOnClickListener(this);
        et_comment_publish_content.addTextChangedListener(this);
        btn_toolbar.setOnClickListener(this);
        rating_comment_publish_score.setOnRatingBarChangeListener(this);

    }

    /**
     * 发布评论
     *
     *            评论内容
     * @param score
     *            星级
     */
    private void publishComment(final String comment, final float score) {

        String json = GsonUtil.toCommentJson(appModel.getAppPackName(), appModel.getRemoteVersionCode(), score, comment);
        HttpUtil.post(json, new StringDialogCallback(AppCommentPublishActivity.this, "正在评论...") {
            @Override
            public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
                //*****************************
                //TODO 上报 发表评论
                String accountId = PreferenceUtils.getInstance(AppCommentPublishActivity.this).getString(PreferenceKey.ACCOUNT_ID);
//				WLData.getInstance().reportEvent(accountId, Events.APP_COMMENT);
                //*****************************

                JsonDataRestult<Object> result = GsonUtil.decode(arg1, new TypeToken<JsonDataRestult<Object>>(){}.getType());
                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                    ToastShow.shortMessage("评论成功");
                    Comment c = new Comment();
                    c.setContent(comment);
                    c.setScore(score);
                    c.setVersion(appModel.getRemoteVersionName());
                    c.setTime(Util.getCurrentUTCTime());
                    Intent data = new Intent();
                    data.putExtra(Constant.DATA, c);
                    setResult(Constant.resultcode, data);
                    finish();

                }else {
                    ToastShow.shortMessage(result.getRetMsg());
                }
            }

            @Override
            public void onError(boolean isFromCache, Call call,
                                Response response, Exception e) {
                if (response == null) {
                    ToastShow.shortMessage(getString(R.string.alert_failed_connect));
                }
                super.onError(isFromCache, call, response, e);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.acb_comment_publish_cancle:
                finish();
                break;
            case R.id.btn_toolbar_button:
            case R.id.acb_comment_publish_publish:
                String content = et_comment_publish_content.getText().toString();
                float score = rating_comment_publish_score.getRating();
                if (score <= 3.5f) {
                    score = 3.5f;
                }
                if (TextUtils.isEmpty(content)) {
                    ToastShow.shortMessage("评论内容不能为空");
                } else if (content.length() > DEFAULT_COMMENT_LENGTH){
                    ToastShow.shortMessage("评论内容不能超过"+DEFAULT_COMMENT_LENGTH+"字");
                }else {
                    publishComment(content, score);
                }
                break;
        }
    }

    /**
     * 评分监听
     */
    @Override
    public void onRatingChanged(RatingBar ratingBar, float rating,
                                boolean fromUser) {
        ratingBar.setRating(rating);
        Log.d("123123", rating+":"+fromUser);
    }

    /**
     * 文本监听
     * @param s
     * @param start
     * @param count
     * @param after
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {

    }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        tv_length.setText(s.length()+"/"+DEFAULT_COMMENT_LENGTH);
    }
    @Override
    public void afterTextChanged(Editable s) {

    }
}
